const stadiumService = require('../service/stadium.service')
const R = require('../utils/R')
const { server } = require('../env')
const { host, port } = server
const {
    GET_STADIUM_DETAIL_EXCEPTION,
    GET_STADIUM_LIST_EXCEPTION,
    GET_STADIUM_CODE_EXCEPTION
} = require('../error/errorType')

class StadiumController {
    // 获取场馆具体信息
    async detail(ctx, next) {
        try {
            let id = ctx.stadiumId
            let [ result ] = await stadiumService.getById(id)
            if (!result) {
                ctx.dto = R.error(GET_STADIUM_DETAIL_EXCEPTION, result)
            }
            if (!result.img) {
                result.img = `http://${host}:${port}/static/IMG_NOT_FOUND.jpg`
            }
            ctx.dto = R.ok('获取场馆具体信息成功', result)
        } catch (err) {
            console.log(err.message)
            return ctx.app.emit('error', new Error(GET_STADIUM_DETAIL_EXCEPTION), ctx)
        }
        await next()
    }

    // 获取场馆列表
    async list(ctx, next) {
        try {
            let word = ctx.word
            let result = await stadiumService.list(word)
            result.forEach(stadium => {
                if (!stadium.img) {
                    result.img = `http://${host}:${port}/static/IMG_NOT_FOUND.jpg`
                }
            })
            ctx.dto = R.ok('获取场馆列表成功', result)
        } catch (err) {
            console.log(err.message)
            return ctx.app.emit('error', new Error(GET_STADIUM_LIST_EXCEPTION), ctx)
        }
        await next()
    }

    async codes(ctx, next) {
        try {
            let stadiums = await stadiumService.list()
            stadiums = stadiums.map(stadium => {
                return { qrcode: `https://quickchart.io/qr?text={stadiumId:${stadium.id}}`, id: stadium.id }
            })
            ctx.dto = R.ok('获取所有场馆二维码成功', stadiums)
        } catch (err) {
            console.log(err.message)
            return ctx.app.emit('error', new Error(GET_STADIUM_CODE_EXCEPTION), ctx)
        }
        await next()
    }
}

module.exports = new StadiumController()